import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { InfraVectorDbInstanceApi } from '#/api/infra/vector/vectorDbInstance';
import type { DescriptionItemSchema } from '#/components/description';

import { h } from 'vue';

import { JsonViewer } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { formatDate } from '@vben/utils';

import { Typography } from 'ant-design-vue';

import DictTag from '#/components/dict-tag/dict-tag.vue';
import { getRangePickerDefaultProps } from '#/utils';

const { Paragraph } = Typography;
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: '实例名称',
      rules: 'required',
      component: 'Input',
      componentProps: {
        placeholder: '请输入实例名称（如 “生产环境 - Milvus 集群”）',
      },
    },
    {
      fieldName: 'type',
      label: '向量库类型',
      rules: 'required',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.INFRA_VECTOR_TYPE),
        placeholder: '请选择向量库类型（milvus/qdrant/pinecone/weaviate 等）',
      },
    },

    {
      fieldName: 'status',
      label: '实例状态',
      rules: 'required',
      component: 'RadioGroup',
      defaultValue: 'online',
      componentProps: {
        options: getDictOptions(DICT_TYPE.INFRA_VECTOR_INSTANCE_STATUS),
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
    {
      fieldName: 'connectionConfig.uri',
      label: '连接地址',
      rules: 'required',
      component: 'Input',
      componentProps: {
        placeholder: '请输入连接地址',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'redisVL' ||
              values.type === 'qdrant' ||
              values.type === 'vectoRex' ||
              values.type === 'milvus')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.caPath',
      label: 'CA证书路径',
      component: 'Input',
      componentProps: {
        placeholder: '请输入CA证书路径（如 /path/to/ca.crt）',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'qdrant'
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.serverUrl',
      label: '服务器URL',
      component: 'Input',
      componentProps: {
        placeholder: '请输入服务器URL',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'opensearch' || values.type === 'elasticsearch')
          );
        },
      },
    },

    {
      fieldName: 'connectionConfig.storePrefix',
      label: '存储前缀',
      component: 'Input',
      componentProps: {
        placeholder: '请输入存储前缀（如 doc:)',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'redisVL'
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.endpoint',
      label: '连接地址',
      component: 'Input',
      componentProps: {
        placeholder: '请输入连接地址',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'aliVectorDB'
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.host',
      label: 'host地址',
      component: 'Input',
      componentProps: {
        placeholder: '请输入连接地址',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'chromaDB' ||
              values.type === 'pgvector' ||
              values.type === 'tencentVectorDB')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.port',
      label: '连接端口',
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入连接端口',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'chromaDB' || values.type === 'pgvector')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.username',
      label: '用户名',
      component: 'Input',
      componentProps: {
        placeholder: '请输入用户名',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'pgvector' ||
              values.type === 'vectoRex' ||
              values.type === 'milvus' ||
              values.type === 'opensearch' ||
              values.type === 'elasticsearch')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.password',
      label: '密码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入密码',
        type: 'password',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'pgvector' ||
              values.type === 'vectoRex' ||
              values.type === 'milvus' ||
              values.type === 'opensearch' ||
              values.type === 'elasticsearch')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.apiKey',
      label: 'API Key',
      component: 'Input',
      componentProps: {
        placeholder: '请输入认证apiKey',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'chromaDB' ||
              values.type === 'qdrant' ||
              values.type === 'opensearch' ||
              values.type === 'elasticsearch' ||
              values.type === 'aliVectorDB' ||
              values.type === 'tencentVectorDB')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.account',
      label: '账号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入账号',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'tencentVectorDB'
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.token',
      label: '认证令牌',
      component: 'Input',
      componentProps: {
        placeholder: '请输入认证令牌',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'milvus'
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.databaseName',
      label: '数据库名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据库名称',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'pgvector' || values.type === 'milvus')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.database',
      label: '数据库名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据库名称',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'chromaDB' ||
              values.type === 'aliVectorDB' ||
              values.type === 'tencentVectorDB')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.defaultCollectionName',
      label: '默认集合',
      component: 'Input',
      componentProps: {
        placeholder: '请输入默认集合（如 collection）',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'redisVL' ||
              values.type === 'pgvector' ||
              values.type === 'qdrant' ||
              values.type === 'vectoRex' ||
              values.type === 'milvus' ||
              values.type === 'aliVectorDB' ||
              values.type === 'tencentVectorDB')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.collectionName',
      label: '默认集合',
      component: 'Input',
      componentProps: {
        placeholder: '请输入默认集合（如 collection）',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'chromaDB'
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.autoCreateCollection',
      label: '自动创建集合',
      component: 'RadioGroup',
      defaultValue: true,
      rules: 'required',
      componentProps: {
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'chromaDB' ||
              values.type === 'pgvector' ||
              values.type === 'qdrant' ||
              values.type === 'vectoRex' ||
              values.type === 'milvus')
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.useHnswIndex',
      label: '启用HNSW索引',
      component: 'RadioGroup',
      defaultValue: false,
      rules: 'required',
      componentProps: {
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        if: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'pgvector'
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.vectorDimension',
      label: '向量维度',
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入向量维度',
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        show: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'pgvector'
          );
        },
      },
    },
    {
      fieldName: 'connectionConfig.defaultIndexName',
      label: '默认索引名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入默认索引名称',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        show: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            (values.type === 'opensearch' || values.type === 'elasticsearch')
          );
        },
      },
    },

    {
      fieldName: 'connectionConfig.clientName',
      label: '客户端名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入客户端名称',
      },
      dependencies: {
        triggerFields: ['connectionConfig', 'type'],
        show: (values) => {
          return (
            values.type !== null &&
            values.type !== '' &&
            values.type !== undefined &&
            values.type === 'pinecone'
          );
        },
      },
    },
    {
      fieldName: 'description',
      label: '实例描述',
      component: 'Textarea',
      componentProps: {
        rows: 4,
        placeholder: '请输入实例描述（如 “支撑产品知识库检索”）',
      },
    },
    {
      fieldName: 'metadata',
      label: '其他参数',
      component: 'Textarea',
      componentProps: {
        rows: 4,
        placeholder: '请输入其他参数',
      },
    },
  ];
}

/** 详情页字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      label: '实例名称',
      field: 'name',
    },
    {
      label: '数据库类型',
      field: 'type',
      render: (val) =>
        h(DictTag, {
          type: DICT_TYPE.INFRA_VECTOR_TYPE,
          value: val,
        }),
    },
    {
      label: '实例状态',
      field: 'status',
      render: (val) =>
        h(DictTag, {
          type: DICT_TYPE.INFRA_VECTOR_INSTANCE_STATUS,
          value: val,
        }),
    },

    {
      label: '连接配置',
      field: 'connectionConfig',
      render: (val) => {
        if (val) {
          return h(JsonViewer, {
            value: val,
            previewMode: true,
          });
        }
        return '';
      },
    },
    {
      label: '实例描述',
      field: 'description',
      render: (val) =>
        h('div', {
          innerHTML: val,
          class: 'whitespace-pre-wrap text-sm leading-relaxed',
        }),
    },
    {
      label: '心跳检测时间',
      field: 'lastHeartbeat',
      render: (val) => formatDate(val) as string,
    },
    {
      label: '其他参数',
      field: 'metadata',
      render: (val) => {
        if (val) {
          return h(JsonViewer, {
            value: val,
            previewMode: true,
          });
        }
        return '';
      },
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'name',
      label: '实例名称',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入实例名称（如 “生产环境 - Milvus 集群”）',
      },
    },
    {
      fieldName: 'type',
      label: '数据库类型',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.INFRA_VECTOR_TYPE),
        placeholder: '请选择数据库类型（milvus/qdrant/pinecone/weaviate 等）',
      },
    },
    {
      fieldName: 'status',
      label: '实例状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.INFRA_VECTOR_INSTANCE_STATUS),
        placeholder: '请选择实例状态（online/offline/error/maintaining）',
      },
    },
    {
      fieldName: 'createTime',
      label: '创建时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<InfraVectorDbInstanceApi.VectorDbInstance>['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '向量库实例id',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'name',
      title: '实例名称',
      minWidth: 200,
    },
    {
      field: 'type',
      title: '数据库类型',
      minWidth: 120,
    },
    {
      field: 'description',
      title: '实例描述',
      minWidth: 300,
    },
    {
      field: 'status',
      title: '实例状态',
      minWidth: 120,
    },
    {
      field: 'createTime',
      title: '创建时间',
      minWidth: 180,
      formatter: 'formatDateTime', // 使用Vben Admin内置的日期时间格式化器
    },
    {
      field: 'lastHeartbeat',
      title: '心跳检测时间',
      minWidth: 120,
      formatter: 'formatDateTime', // 使用Vben Admin内置的日期时间格式化器
    },
    {
      field: 'actions',
      title: '操作',
      width: 280,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
